<?php
/**
 * 渠道管理控制器
*
* PHP version 5
*
* @package   Ecga
* @author    Farmer.Li <lixu_01@126.com>
* @copyright 2010 Xingchangxinda Inc.
* @version   SVN: $Id$
*/
namespace Project\Apps\Ecga\Controllers;

use \Project\Apps\Ecga\Controllers\Abstraction\EcgaController;
use \Framework\System\Helper\HttpResponse;
use \Project\Apps\Ecga\Models\Sites as SitesBiz;
use \Framework\Controller\ControllerException;
use \Framework\Mapper\FieldException;

use \Project\Apps\Ecga\Library\Visitor;

/**
 * 渠道管理控制器
 *
 * PHP version 5
 *
 * @package   Ecga
 * @author    Farmer.Li <lixu_01@126.com>
 * @copyright 2010 Xingchangxinda Inc.
 * @version   Release: <0.1>
 **/
class Sites extends EcgaController
{
    
    //
    
    /**
     * 显示数据表
     *
     * @param HttpRequest $request Http请求
     *
     * @return void
     */
    public static function show($request)
    {
        $page = self::createPage();
        $page->setTitle('渠道列表');
        $pageNo = $request->get('page', 'int', 1);
        $projectIds = model('userprojectprivs')->getProjectByUserId(parent::$visitor->userId);
        $list = self::createDataList(SitesBiz::getPageQuery($projectIds, parent::$visitor->isBoss()))
            ->setCurrentPage($pageNo)
            ->orderBy('id', 'desc');
        foreach ($list as $value) {
            foreach (self::_getProjectToOption() as $key => $projects) {
                if ($key == $value['projectId']) {
                    $projectName[$value['id']] = $projects;
                }
            } 
        }
        $page->assign('projects', self::_getProjectToOption());
        $page->assign('projectName', $projectName);
        $page->assign('isBoss', parent::$visitor->isBoss());
        $page->assign('list', $list);
        HttpResponse::output($page->render('sitelist'));
    }
    
    /**
     * 添加渠道
     * 
     * @param HttpRequest $request Http请求
     * 
     * @return void
     */
    public static function add($request)
    {
        $page = self::createPage();
        $page->setTitle('添加渠道');
        $page->assign('projects', self::_getProjectToOption());
        $page->assign('checkRegion', self::checkRegion());
        HttpResponse::output($page->render('sitedetail'));
    }
    
    /**
     * 执行添加项目
     *
     * @param HttpRequest $request Http请求
     *
     * @return void
     */
    public static function doAdd($request) 
    {
        $data = self::_getFormData($request);
        $site = model('Sites')->create();
        if ( 0 == $data['projectId']) {
            $data['projectId'] = key(self::_getProjectToOption());
        }
        try {
            self::_save($site, $data);
        } catch (ControllerException $e) {
            HttpResponse::jsonResult(false, $e->getMessage());
            return false;
        }
        
        $msg = '已成功添加渠道 ' . $data['cname'];
        self::message($msg);
        HttpResponse::jsonResult(true, $msg);
    }
    
    /**
     * 编辑项目
     *
     * @param HttpRequest $request Http请求
     *
     * @return void
     */
    public static function edit($request)
    {
        $page = self::createPage();
        $page->setTitle('编辑渠道');
        $id = $request->get('id', 'int');
        $site = model('Sites')->get($id);
        if (!$site) {
            self::message('未找到指定渠道', 'warning', 'sites.php?a=show');
            return false;
        }
        foreach (self::_getProjectToOption() as $key => $projects) {
            if ($key == $site['projectId']) {
                $projectName = $projects;
            }
        }
        $page->assign('projects', self::_getProjectToOption());
        $page->assign('projectName', $projectName);
        $page->assign('isBoss', parent::$visitor->isBoss());
        $page->assign('site', $site);
		$page->assign('checkRegion', self::checkRegion());
        HttpResponse::output($page->render('sitedetail'));
    }
    /**
     * 获取有权限的项目 option数组格式
     * 
     * @return array
     */
    private static function _getProjectToOption()
    {
        static $projects = null;
        if (null != $projects) {
            return $projects;
        }
        $ns = get_called_class();
        $tableName = substr($ns, strrpos($ns, '\\') + 1);
        $projects = model('Projects')->getOptions();
        if ($projects) {
            $passport = parent::$visitor->getPassport();
            foreach ($projects as $key => $value) {
                //去除没有查看权限的项目
                if (!$passport->hasProjectPriviage($key, $tableName)) {
                    unset($projects[$key]);
                }
            }
        }
        return $projects;
    }
    /**
     * 执行编辑项目
     *
     * @param HttpRequest $request Http请求
     *
     * @return void
     */
    public static function doEdit($request)
    {
        $id = $request->get('id', 'int');
        $site = model('Sites')->get($id);
        if (!$site) {
            self::message('未找到指定项目', 'warning', 'sites.php?a=show');
            return false;
        }
        $data = self::_getFormData($request);
        if (0 == $data['projectId']) {
            $data['projectId'] = key(self::_getProjectToOption());
        }
        try {
            self::_save($site, $data);
        } catch (ControllerException $e) {
            HttpResponse::jsonResult(false, $e->getMessage());
            return false;
        }        
        $msg = '已成功修改渠道' . $data['cname'];
        self::message($msg);
        HttpResponse::jsonResult(true, $msg);
    }
    
    /**
     * 获取表单数据
     * 
     * @param HttpRequest $request Http请求
     * 
     * @return array
     */
    private static function _getFormData($request)
    {
        $data = array (
                'cname' => $request->post('cname', 'string'),
                'ename' => $request->post('ename', 'string'),
                'siteUrl' => $request->post('siteUrl', 'string'),
                'projectId' => $request->post('projectId', 'int'),
                'region' => $request->post('region', 'int'),
                'tag' => $request->post('tag', 'string')
            );
        return $data;
    }
    
    /**
     * 执行保存动作
     *
     * @param entity $entity 模型实体
     * @param array  $data   项目数据
     * 
     * @return void
     */
    private static function _save($entity, $data)
    {
        try {
            $entity->setAttributes($data)->save();
        } catch (FieldException $e) {
            switch ($e->getCode()) {
            case FieldException::BLANK_VALUE :
                if ($e->field == 'cname') {
                    $message = '对不起，中文名称不能为空。';
                } elseif ($e->field == 'ename') {
                    $message = '对不起，英文名称不能为空。';
                } elseif ($e->field == 'siteName') {
                    $message = '对不起，地址不能为空。';
                } else {
                    throw $e;
                }
                break;
            case FieldException::UNIQUE_VALUE :
                $message = '对不起，相同名称的渠道已存在。';
                break;
            case FieldException::INVALUD_VALUE :
                break;
            default :
                throw $e;
            }
            throw new ControllerException($message);
        }
    }
	
	/**
     * 验证渠道东西南北区
     * 
     * @return array
     */
    public static function checkRegion()
    {
        $return = array(
			'0' => '无',
			'1' => '东',
			'2' => '西',
			'3' => '南',
			'4' => '北'
		);
    
        return $return;
    }
}
?>